package com.api.aron.utils;

import org.apache.axis.encoding.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import weaver.conn.RecordSet;
import weaver.docs.webservices.DocAttachment;
import weaver.docs.webservices.DocInfo;
import weaver.docs.webservices.DocService;
import weaver.docs.webservices.DocServiceImpl;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestService;
import weaver.systeminfo.SystemEnv;
import weaver.wechat.util.Utils;
import weaver.workflow.msg.PoppupRemindInfoUtil;
import weaver.workflow.request.ComparatorUtilBean;
import weaver.workflow.request.RequestAddShareInfo;
import weaver.workflow.request.RequestNodeFlow;
import weaver.workflow.request.WFLinkInfo;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 〈工具类〉
 *
 * @author Administrator
 * @create 2020/3/10
 * @since 1.0.0
 */
public class CommonUtils {
    private static Logger logger = LoggerFactory.getLogger(BpmUtils.class);
    private static BaseBean basebean = new BaseBean();

    public CommonUtils() {
        super();
    }

    /**
     * 获取下拉框值
     *
     * @param selectvalue 下拉框值
     * @param billid      流程表单
     * @param fieldname   数据库字段名
     * @return
     */
    public static String getSelectItme(Integer selectvalue, Integer billid, String fieldname) {
        RecordSet rs = new RecordSet();
        String sql = "select selectname from workflow_selectitem where selectvalue = ? and fieldid in (select id from workflow_billfield where billid=? and fieldname=?)";
        rs.executeQuery(sql, selectvalue, billid, fieldname);
        rs.next();
        return "" + rs.getString("selectname");
    }

    /**
     * 新建流程字段赋值
     *
     * @param fieldName
     * @param value
     * @return
     */
    public static Property setField(String fieldName, String value) {
        Property p = new Property();
        p.setName(fieldName);
        p.setValue(value);
        return p;
    }

    /**
     * 字符串判断为空
     *
     * @param str
     * @return
     */
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取流程表名
     *
     * @param workflowid 流程id
     * @return
     */
    public static String getTableNameByWorkflowid(String workflowid) {
        String formid = "";
        String sql = "select fromid from workflow_base where id =?";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, workflowid);
        if (rs.next()) {
            formid = rs.getString("fromid");
        }
        formid = formid.replaceAll("-", "");
        String tablename = "formtable_main_" + formid;
        return tablename;
    }

    /**
     * 获取年月日
     * yyyy-MM-dd
     *
     * @return
     */
    public static String getYearMothDay() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(cal.getTime());
        return time;
    }

    /**
     * 流程转发
     *
     * @param requestids      多流程
     * @param forwardoperator 当前操作者
     * @param recients        被转发人
     * @return
     */
    public static boolean forwardFlow(String requestids, int forwardoperator, String recients) {
        String[] requestid = requestids.split(",");
        try {
            for (int i = 0; i < requestid.length; i++) {
                RequestService reqSvc = new RequestService();
                reqSvc.forwardFlow(Integer.parseInt(requestid[i]), forwardoperator, recients, "", "");
            }
        } catch (Exception e) {
            logger.error("forwardFlow出错：" + e);
        }
        return true;
    }

    /**
     * 根据人员id获取上级
     *
     * @param id
     * @return
     */
    public static Integer getManagerByUserid(Integer id) {
        RecordSet rs = new RecordSet();
        String sql = "select managerid from hrmresource where id = ?";
        rs.executeQuery(sql, id);
        rs.next();
        return Utils.getIntValue(rs.getString("managerid"), 0);
    }

    /**
     * 创建附件文档
     *
     * @param filePath
     * @param fileName
     * @param docSubject
     * @param docContent
     * @param userId         ecology用户登录名
     * @param userPassword   ecology登录密码
     * @param domianName     域名
     * @param maincategoryId 文档主目录id
     * @param subcategoryId  文档子目录id
     * @param seccategoryId  子目录的子目录id
     * @return
     * @throws Exception
     */
    public static int createAttenchment(String filePath, String fileName, String docSubject, String docContent, String userId, String userPassword, String domianName, int maincategoryId, int subcategoryId, int seccategoryId) throws Exception {
        DocService docService = new DocServiceImpl();
        String seesionInfo = docService.login(userId, userPassword, 0, domianName);
        DocInfo doc = new DocInfo();
        DocAttachment da = new DocAttachment();
        da.setDocid(0);
        da.setImagefileid(0);
        da.setFilename(fileName);
        da.setFilecontent(Base64.encode(InputStream2ByteArray(filePath)));
        da.setFilerealpath(filePath);
        da.setIszip(1);

        doc.setId(0);
        doc.setDocSubject(docSubject);
        doc.setDoccontent(docContent);
        doc.setMaincategory(maincategoryId);
        doc.setSubcategory(subcategoryId);
        doc.setSeccategory(seccategoryId);
        doc.setAttachments(new DocAttachment[]{da});
        int docId = docService.createDoc(doc, seesionInfo);
        return docId;
    }

    public static byte[] InputStream2ByteArray(String filePath) {
        InputStream in = null;
        ByteArrayOutputStream out = null;
        byte[] data = null;
        try {
            in = new FileInputStream(filePath);
            out = new ByteArrayOutputStream();
            data = toByteArray(in, out);
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data;
    }

    public static byte[] toByteArray(InputStream in, ByteArrayOutputStream out) throws IOException {
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    /**
     * 获取节点名称
     *
     * @param nodeid 节点id
     * @return
     */
    public static String getNodeName(int nodeid) {
        RecordSet rs = new RecordSet();
        String nodename = "";
        String sql = "select nodename from workflow_nodebase where id = ?";
        if (rs.executeQuery(sql, nodeid) && rs.next()) {
            nodename = Util.null2String(rs.getString("nodename"));
        }
        return nodename;
    }

    /**
     * 获取当前日期
     * yyyy-MM-dd
     *
     * @return
     */
    public static String getCurrentDay() {
        Long millsTime = System.currentTimeMillis();
        Date date = new Date(millsTime);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(date);
    }

    /**
     * 获取当前时间
     * HH:mm
     *
     * @return
     */
    public static String getCurrentTime() {
        Long millsTime = System.currentTimeMillis();
        Date date = new Date(millsTime);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        return simpleDateFormat.format(date);
    }

    /**
     * 计算2个日期之间相差的天数
     *
     * @param sdate 较前的日期
     * @param edate 较后的日期
     * @return
     * @throws ParseException
     */
    public static int daysBetween(String sdate, String edate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date smdate = sdf.parse(sdate);
        Date bdate = sdf.parse(edate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        Long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        Long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 % 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 数字金额大写转换
     *
     * @param n
     * @return
     */
    public static String digitUppercase(double n) {
        String[] fraction = {"角", "分"};
        String[] digit = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
        String[][] unit = {{"元", "万", "亿"}, {"", "拾", "佰", "仟"}};
        String head = n < 0 ? "负" : "";
        n = Math.abs(n);
        String s = "";
        for (int i = 0; i < fraction.length; i++) {
            s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i].replaceAll("(零.)+", ""));
        }
        if (s.length() < 1) {
            s = "整";
        }
        int integerPart = (int) Math.floor(n);
        for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
            String p = "";
            for (int j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[integerPart % 10] + unit[1][j] + p;
                integerPart = integerPart / 10;
            }
            s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
        }
        return head.replaceAll("(零.)*零元", "元").replaceAll("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
    }

    /**
     * 多语言文本格式化，根据语言ID格式化出对应语言
     *
     * @param nr
     * @param languages
     * @return
     */
    public static String i18nFormatText(String nr, String languages) {
        if (nr == null) {
            return "";
        }
        String wb = nr;
        if (wb.indexOf("~`~`") >= 0 && wb.indexOf("`~`~") >= 0) {
            wb = wb.substring(nr.indexOf("~`~`"), wb.indexOf("`~`~"));
            for (String s1 : wb.split("`~`")) {
                String[] ss1 = s1.split(" ");
                if (ss1.length > 1 && ss1[0].equals(languages)) {
                    return s1.substring(s1.indexOf(" ") + 1);
                }
            }
        }
        return nr;
    }

    /**
     * 强制归档
     *
     * @param requestids
     */
    public static void doForceOver(ArrayList requestids) {
        RecordSet rs = new RecordSet();
        User user = getUserfromDB("1");
        String requestid = "";
        Hashtable operatorsht = new Hashtable();
        int currNodeId = -1;
        int currNodeType = -1;
        String billtableName = "";
        String requestname = "";
        int formid = -1;
        int isbill = -1;
        int billid = -1;
        int totalgroups = 0;
        int currentNodeId = -1;
        int currentNodeType = -1;
        int wfid = -1;
        int wftype = -1;
        int requestlevel = -1;
        int creater = -1;
        int creatertype = -1;
        int userid = 0;//强制归档人
        int usertype = 1;
        int userlanuage = 7;
        int isreopen = 0;
        int isreject = 0;
        PoppupRemindInfoUtil poppupRemindInfoUtil = new PoppupRemindInfoUtil();
        boolean hasnextnodeoperator = false;
        String Procpara = "";
        Calendar today = Calendar.getInstance();
        String CurrentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        String CurrentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + Util.add0(today.get(Calendar.SECOND), 2);
        char flag = Util.getSeparator();
        for (int i = 0; i < requestids.size(); i++) {
            requestid = (String) requestids.get(i);
            rs.executeProc("workflow_Requestbase_SByID", requestid + "");
            if (rs.next()) {
                requestname = rs.getString("requestname");
                currNodeId = rs.getInt("currentnodeid");
                requestlevel = rs.getInt("requestlevel");
                wfid = rs.getInt("workflowid");
                creater = Util.getIntValue(rs.getString("creater"), 0);
                creatertype = Util.getIntValue(rs.getString("creatertype"), 0);
                currNodeType = Util.getIntValue(rs.getString("currentnodetype"), 0);
            }
            String sql = "select nodeid from workflow_flownode where workflowid = ? and nodetype = 3";
            rs.executeQuery(sql, wfid);
            if (rs.next()) {
                currentNodeId = rs.getInt("nodeid");
                currNodeType = 3;
            }
            sql = "select workflowtype from workflow_base where id = ?";
            rs.executeQuery(sql, wfid);
            if (rs.next()) {
                wftype = rs.getInt("workflowtype");
            }
            rs.executeProc("workflow_Workflowbase_SByID", "" + wfid);
            if (rs.next()) {
                isbill = Util.getIntValue(rs.getString("isbill"), -1);
                formid = Util.getIntValue(rs.getString("formid"), -1);
            }
            if (isbill == 1) {
                sql = "select tablename from workflow_bill where id = ?";
                rs.executeQuery(sql, formid);
                if (rs.next()) {
                    billtableName = rs.getString("tablename");
                }
            }
            if (isbill == 1 && !"".equals(billtableName)) {
                sql = "select id from " + billtableName + " where requestid = ?";
                rs.executeQuery(sql, requestid);
                if (rs.next()) {
                    billid = rs.getInt("id");
                }
            }
            if (currentNodeType == 0) {
                isreopen = 1;
            }
            int prenodeid = 0;
            String prenodetype = "0";
            sql = "select * from workflow_nodelink where wfrequestid is null and workflowid = ? and destnodeid = ? and ((isreject <>'1' and condtion ='') or (isreject is null and condition is null)) order by nodepasstime,id";
            rs.executeQuery(sql, wfid, currentNodeId);
            if (rs.next()) {
                prenodeid = rs.getInt("nodeid");
                isreject = Util.getIntValue(rs.getString("isreject"), 0);
            }
            sql = "select * from workflow_flownode where workflowid = ? and nodeid = ?";
            rs.executeQuery(sql, wfid, prenodeid);
            if (rs.next()) {
                prenodetype = rs.getString("nodetype");
            }
            try {
                RequestNodeFlow requestNodeFlow = new RequestNodeFlow();
                ResourceComInfo resourceComInfo = new ResourceComInfo();
                //按照归档节点操作人条件设置强制归档接收人
                requestNodeFlow.setRequestid(Integer.parseInt(requestid));
                requestNodeFlow.setNodeid(prenodeid);
                requestNodeFlow.setNodetype(prenodetype);
                requestNodeFlow.setWorkflowid(wfid);
                requestNodeFlow.setUserid(userid);
                requestNodeFlow.setUsertype(usertype);
                requestNodeFlow.setCreaterid(creater);
                requestNodeFlow.setCreatertype(creatertype);
                requestNodeFlow.setIsbill(isbill);
                requestNodeFlow.setBillid(billid);
                requestNodeFlow.setBilltablename(billtableName);
                requestNodeFlow.setIsreject(isreject);
                requestNodeFlow.setIsreopen(isreopen);
                requestNodeFlow.setRecordSet(rs);
                hasnextnodeoperator = requestNodeFlow.getNextOperator();
                if (hasnextnodeoperator) {
                    operatorsht = requestNodeFlow.getOperators();
                } else {//当运算归档节点接收人为空时，同时归档至流程创建人与当前操作人处
                    ArrayList arr = new ArrayList();
                    arr.add(creater + "_" + creatertype + "_0");
                    operatorsht.put("1", arr);
                    if (!(creater + "_" + creatertype).equals(userid + "_" + usertype)) {
                        arr = new ArrayList();
                        arr.add(userid + "_0" + "_" + "-1");
                        operatorsht.put("2", arr);
                    }
                }
                //更新workflow_requestbase
                float nodepasstime = 0;
                String status = SystemEnv.getHtmlLabelName(18360, userlanuage);
                rs.executeProc("workflow_NodeLink_SPasstime", "" + currentNodeId + flag + "0");
                if (rs.next()) {
                    nodepasstime = Util.getIntValue(rs.getString("nodepasstime"), -1);
                }
                sql = " update workflow_requestbase set lastnodeid = " + currNodeId + ",lastnodetype='" + currNodeType + "',currentnodeid=" + currentNodeId + ",currentnodetype=?,status=?,passedgroups=0,totalgroups=?,lastoperator=?,lastoperatedate=?,lastoperatetime=?,lastoperatortype=?,nodepasstime=?,nodelefttime=? where requestid = ?";
                rs.executeQuery(sql, currNodeId, currNodeType, currentNodeId, currentNodeType, status, operatorsht.size(), userid, CurrentDate, CurrentTime, usertype, nodepasstime, nodepasstime, requestid);
                //更新当前节点表
                WFLinkInfo wfLinkInfo = new WFLinkInfo();
                int nodeattr = wfLinkInfo.getNodeAttribute(currentNodeId);
                sql = "delete from workflow_nownode where requestid = ?";
                rs.executeQuery(sql, requestid);
                sql = "insert into workflow_nownode(requestid,nownodeid,nownodetype,nownodeattribute) values (?,?,?,?)";
                rs.executeQuery(sql, requestid, currentNodeId, currentNodeType, nodeattr);
                //添加归档节点操作人，考虑代理
                String agentSQL = "";
                boolean isbeAgent = false;
                String agenterId = "";
                String beginDate = "";
                String beginTime = "";
                String endDate = "";
                String endTime = "";
                String currentDate = "";
                String currentTime = "";
                String agenttype = "";
                //更新到流程提醒信息
                sql = "select userid,usertype from workflow_currentoperator where requestid =? and nodeid = ? and isremark in ('0','1','8','9','7')";
                rs.executeQuery(sql, requestid, currNodeId);
                while (rs.next()) {
                    poppupRemindInfoUtil.updatePoppupRemindInfo(rs.getInt(1), 0, "" + rs.getInt(2), Integer.parseInt(requestid));
                }
                sql = "update workflow_currentoperator set isremark = '2' where requestid = ? and nodeid = ? and isremark in ('0','1','8','9','7')";
                rs.executeQuery(sql, requestid, currNodeId);
                int showorder = 0;
                String tempHrmIds = "";
                TreeMap map = new TreeMap(new ComparatorUtilBean());
                Enumeration tempKeys = operatorsht.keys();
                while (tempKeys.hasMoreElements()) {
                    String tempKey = (String) tempKeys.nextElement();
                    ArrayList tempoperators = (ArrayList) operatorsht.get(tempKey);
                    map.put(tempKey, tempoperators);
                }
                Iterator iterator = map.keySet().iterator();
                while (iterator.hasNext()) {
                    String operatorgroup = (String) iterator.next();
                    ArrayList operators = (ArrayList) operatorsht.get(operatorgroup);
                    for (int h = 0; h < operators.size(); h++) {
                        showorder++;
                        String operatorandtype = (String) operators.get(h);
                        String[] operatorandtypes = Util.TokenizerString2(operatorandtype, "_");
                        String opertor = operatorandtypes[0];
                        String opertortype = operatorandtypes[1];
                        int groupdetailIds = Util.getIntValue(operatorandtypes[2], -1);
                        isbeAgent = false;
                        agentSQL = "select * from WORKFLOW_AGENT where workflowId = ? and beagenterId =? and agenttype ='1' " +
                                "and (((endDate = ? and (endTime ='' " +
                                "or endTime is null)) or (endDate = '' and endTime>?)) or endDate >? or endDate = '' or endDate is null)" +
                                "and (((beginDate = ? and (beginTime='' or beginTime is null)) or (beginDate =? and beginTime <?)) " +
                                "or beginDate <? or beginDate ='' or beginDate is null)";
                        rs.executeQuery(sql, wfid, opertor, CurrentDate, CurrentDate, CurrentTime, CurrentDate, CurrentDate, CurrentDate, CurrentTime, CurrentDate);
                        if (rs.next()) {
                            isbeAgent = true;
                            agenterId = rs.getString("agenterId");
                            beginDate = rs.getString("beginDate");
                            beginTime = rs.getString("benginTime");
                            endDate = rs.getString("endDate");
                            endTime = rs.getString("endTime");
                            currentDate = TimeUtil.getCurrentDateString();
                            currentTime = TimeUtil.getCurrentTimeString().substring(11, 19);
                            agenttype = rs.getString("agenttype");
                        }
                        if (isbeAgent) {
                            //设置被代理人已操作
                            Procpara = "" + requestid + flag + opertor + flag + operatorgroup + flag + wfid + flag + wftype + flag + opertortype + flag + "2" + flag + currentNodeId + flag + agenterId + flag + "1" + flag + showorder + flag + groupdetailIds;
                            rs.executeProc("workflow_CurrentOperator_I", Procpara);
                            Procpara = "" + requestid + flag + agenterId + flag + operatorgroup + flag + wfid + flag + wftype + flag + opertortype + flag + "0" + flag + currentNodeId + flag + opertor + flag + "2" + flag + showorder + flag + groupdetailIds;
                            rs.executeProc("workflow_CurrentOperator_I", Procpara);
                        } else {
                            Procpara = "" + requestid + flag + opertor + flag + operatorgroup + flag + wfid + flag + wftype + flag + opertortype + flag + "0" + currentNodeId + flag + -1 + flag + "0" + showorder + flag + groupdetailIds;
                            rs.executeProc("workflow_CurrentOperator_I", Procpara);
                        }
                        if (!isbeAgent) {
                            tempHrmIds += Util.toScreen(resourceComInfo.getResourcename(opertor), userlanuage) + ",";
                        } else {
                            tempHrmIds += Util.toScreen(resourceComInfo.getResourcename(opertor), userlanuage) + "->" + Util.toScreen(resourceComInfo.getResourcename(agenterId), userlanuage) + ",";
                        }
                        //已完成流程信息数量
                        if (!isbeAgent) {
                            poppupRemindInfoUtil.insertPoppupRemindInfo(Integer.parseInt(opertor), 1, "" + opertortype, Integer.parseInt(requestid));
                        } else {
                            poppupRemindInfoUtil.insertPoppupRemindInfo(Integer.parseInt(agenterId), 1, "" + opertortype, Integer.parseInt(requestid));
                        }
                    }
                }
                if (currentNodeType == 3) {
                    sql = "update workflow_currentoperator set isremark = '4' where isremark = '0' and requestid = ?";
                    rs.executeQuery(sql, requestid);
                    sql = "update workflow_currentoperator set iscomplete = 1 where requestid = ?";
                    rs.executeQuery(sql, requestid);
                }
                //任务强制归档后，保留强制归档记录：“强制归档”类型代码为“e”
                sql = "select agentorbyagentid,agenttype,showorder from workflow_currentoperator where userid = ? and  nodeid = ? and isremark  in ('0','1','4','8','7','9') and requestid = ?";
                rs.executeQuery(sql, userid, currNodeId, requestid);
                if (rs.next()) {
                    showorder = rs.getInt("showorder");
                }
                String remark = "";
                RequestAddShareInfo shareInfo = new RequestAddShareInfo();
                shareInfo.setRequestid(Util.getIntValue(requestid));
                shareInfo.SetWorkFlowID(wfid);
                shareInfo.SetNowNodeID(currNodeId);
                shareInfo.SetNextNodeID(currentNodeId);
                shareInfo.setIsbill(isbill);
                shareInfo.setUser(user);
                shareInfo.SetIsWorkFlow(1);
                shareInfo.setBillTableName(billtableName);
                shareInfo.setHaspassnode(true);
                shareInfo.addShareInfo();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //是否反馈
            String isfeedback = "";//当前节点是否反馈
            sql = "select isfeedback from workflow_flownode where workflowid = ? and nodeid = ?";
            rs.executeQuery(sql, wfid, currNodeId);
            if (rs.next()) {
                isfeedback = Util.null2String(rs.getString("isfeedback"));
            }
            String ischagestatus = Util.null2String(basebean.getPropValue(GCONST.getConfigFile(), "ecology.changestatus"));//总开关
            if (!"".equals(ischagestatus) && "1".equals(isfeedback)) {
                sql = "update workflow_currentoperator set viewtype = 1 where needwfback = '1' and requestid = ? and viewtype = -2";
                rs.executeQuery(sql, requestid);
            }
        }
    }

    private static User getUserfromDB(String id) {
        RecordSet rs = new RecordSet();
        User user = new User();
        String sql = "select id,firstname,lastname,systemlanguage,seclevel,loginid from HrmResourceManager where id =?";
        rs.executeQuery(sql, id);
        if (rs.next()) {
            user.setUid(rs.getInt("id"));
            user.setLocationid(rs.getString("loginid"));
            user.setFirstname(rs.getString("lastname"));
            user.setLanguage(Util.getIntValue(rs.getString("systemlanguage"), 0));
            user.setSeclevel(rs.getString("seclevel"));
            user.setLogintype("1");
        }
        rs.execute("HrmResource_SelectByID", id);
        if (rs.next()) {
            user.setUid(rs.getInt("id"));
            user.setLoginid(rs.getString("loginid"));
            user.setFirstname(rs.getString("firstname"));
            user.setLastname(rs.getString("lastname"));
            user.setAliasname(rs.getString("aliasname"));
            user.setTitle(rs.getString("title"));
            user.setTitlelocation(rs.getString("titlelocation"));
            user.setSex(rs.getString("sex"));
            user.setLanguage(Util.getIntValue(rs.getString("systemlanguage"), 0));
            user.setTelephone(rs.getString("telephone"));
            user.setMobile(rs.getString("mobile"));
            user.setMobilecall(rs.getString("mobilecall"));
            user.setEmail(rs.getString("email"));
            user.setCountryid(rs.getString("countryid"));
            user.setLocationid(rs.getString("locationid"));
            user.setResourcetype(rs.getString("resourcetype"));
            user.setStartdate(rs.getString("stratdate"));
            user.setEnddate(rs.getString("enddate"));
            user.setContractdate(rs.getString("contractdate"));
            user.setJobtitle(rs.getString("jontitle"));
            user.setJobgroup(rs.getString("jobgroup"));
            user.setJobactivity(rs.getString("jobactivity"));
            user.setJoblevel(rs.getString("joblevel"));
            user.setSeclevel(rs.getString("seclevel"));
            user.setUserDepartment(Util.getIntValue(rs.getString("department"), 0));
            user.setUserSubCompany1(Util.getIntValue(rs.getString("subcompanyid1"), 0));
            user.setUserSubCompany2(Util.getIntValue(rs.getString("subcompanyid2"), 0));
            user.setUserSubCompany3(Util.getIntValue(rs.getString("subcompanyid3"), 0));
            user.setUserSubCompany4(Util.getIntValue(rs.getString("subcompanyid4"), 0));
            user.setManagerid(rs.getString("managerid"));
            user.setAssistantid(rs.getString("assistantid"));
            user.setPurchaselimit(rs.getString("purchaselimit"));
            user.setCurrencyid(rs.getString("currencyid"));
            user.setLastlogindate(rs.getString("lastlogindate"));
            user.setLogintype("1");
        }
        return user;
    }

    /**
     * 获取表单字段FieldId
     *
     * @param formid
     * @return
     */
    public static Map<String, String> getFieldid(int formid) {
        String sql = "select * from workflow_billfield where billid = ? order by viewtype ";
        Map<String, String> fields = new HashMap<String, String>();
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, formid);
        while (rs.next()) {
            String viewType = "0";
            String detailtable = Util.null2String(rs.getString("detailtable"));
            if (detailtable.lastIndexOf("_dt") > 0) {
                viewType = detailtable.substring(detailtable.lastIndexOf("_dt") + 3);
            }
            String fieldname = rs.getString("fieldname");
            String fieldid = rs.getString("id");
            fields.put(fieldname + "_" + viewType, fieldid);
        }
        return fields;
    }

}